package com.bluedot.bank.dao.exchangerecord;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.bluedot.bank.dao.HibernateDaoSupport;
import com.bluedot.bank.dao.Pagination;

public class ExchangeRecordDaoImpl extends
		HibernateDaoSupport<ExchangeRecord, Long> implements ExchangeRecordDao {

	public ExchangeRecordDaoImpl() {
		this.entityClass = ExchangeRecord.class;
	}

	@Override
	public void browse(Pagination<ExchangeRecord> pagination) {
		Session session = this.getSession();
		RecordFilter filter=(RecordFilter)pagination.getConditon();
		DetachedCriteria dc = DetachedCriteria.forClass(ExchangeRecord.class);
		switch (filter.getFilterName()) {
		case 1:
			dc.add(Restrictions.between("exchange_time", filter.getBegin_time(), filter.getEnd_time()));
			break;
		case 2:
			dc.add(Restrictions.eq("id", Long.parseLong(filter.getValuekey())));
			//dc.add(Restrictions.between("check_time", filter.getBegin_time(), filter.getEnd_time()));
			break;
		case 3:
			dc.add(Restrictions.eq("account_id", Long.parseLong(filter.getValuekey())));
			dc.add(Restrictions.between("exchange_time", filter.getBegin_time(), filter.getEnd_time()));
			break;
		case 4:
			dc.add(Restrictions.like("description", filter.getValuekey(),MatchMode.ANYWHERE));
			dc.add(Restrictions.between("exchange_time", filter.getBegin_time(), filter.getEnd_time()));
			break;

		default:			
			break;
		}

		Criteria criteria = dc.getExecutableCriteria(session);
        
		Integer count = (Integer) criteria.setProjection(
				Projections.count(Projections.id().toString())).uniqueResult();
		pagination.setRecordSum(count);

		if (pagination.getRecordSum() > 0) {
			criteria = dc.getExecutableCriteria(session);

			if (pagination.getOrderFieldName() != null
					&& !pagination.getOrderFieldName().trim().isEmpty()) {
				criteria.addOrder(pagination.isDesc() ? Order.desc(pagination
						.getOrderFieldName()) : Order.asc(pagination
						.getOrderFieldName()));
			}

			criteria.setFirstResult(pagination.getSize()
					* (pagination.getNo() - 1));
			criteria.setMaxResults(pagination.getSize());
			pagination.setResults(criteria.list());
		}
	}
}
